﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pibby.Core.Tests.Stubs
{
	public class RandomText
	{
		private static Random _random = new Random();

		StringBuilder _builder;

		public RandomText()
		{
			this.Words = new List<string>();

			this.MaxParagraphSentences = 5;
			this.MinParagraphSentences = 1;
			this.Paragraphs = 1;
			this.MinSentenceWords = 3;
			this.MaxSentenceWords = 20;
		}

		public RandomText(IEnumerable<string> words)
			: this ()
		{
			this.Words.AddRange (words);
		}


		public int Paragraphs
		{
			get;
			set;
		}

		public int MinParagraphSentences
		{
			get;
			set;
		}
		
		public int MaxParagraphSentences
		{
			get;
			set;
		}

		public int MinSentenceWords
		{
			get;
			set;
		}

		public int MaxSentenceWords
		{
			get;
			set;
		}

		public List<string> Words
		{
			get;
			private set;
		}

		private StringBuilder Builder
		{
			get
			{
				if (this._builder == null)
					this._builder = new StringBuilder();

				return this._builder;
			}
			set
			{
				this._builder = value;
			}
		}

		public void Generate()
		{
			this._builder = new StringBuilder ();

			for (int i = 0; i < this.Paragraphs; ++i)
			{
				GenerateParagraph(_random.Next(this.MinParagraphSentences, this.MaxParagraphSentences + 1));
				this.Builder.Append("\n\n");
			}
		}
		/// <summary>
		/// Add single pararaph consisting of several sentences.
		/// </summary>
		void GenerateParagraph(int numberSentences)
		{
			for (int i = 0; i < numberSentences; ++i)
			{
				GenerateSentence(_random.Next(this.MinSentenceWords, this.MaxSentenceWords + 1));
			}
		}

		private void GenerateSentence(int numberWords)
		{
			for (int i = 0; i < numberWords; ++i)
			{
				string randomWord = this.Words[_random.Next(this.Words.Count)];

				if (i == 0)
				{
					this.Builder.AppendFormat("{0}{1} ", char.ToUpper(randomWord[0]), randomWord.Substring(1));
				}
				else if (i == (numberWords - 1))
				{
					this.Builder.AppendFormat("{0}. ", randomWord);
				}
				else
				{
					this.Builder.AppendFormat("{0} ", randomWord);
				}
			}
		}

		public override string ToString ()
		{
			return this.Builder.ToString();
		}
	}
}
